/**
 * Created by 游永年 on 2019-02-23 11:36.
 * 下一题的button
 */

import {Button, Modal} from "antd-mobile";
import {connect} from 'dva';
import React, {Component} from 'react';
import {withRouter} from "react-router-dom";

const alert = Modal.alert;

@withRouter
class NextButton extends Component {
  constructor(...props) {
    super(...props);
    this.state = {
      disabled: false,
    };
  }

  render() {
    return (
      <div style={{width: '50%'}}>
        <Button onClick={this.onClick} type={'primary'} disabled={this.state.disabled}>
          {this.isLast() ? '交卷' : '下一题'}
        </Button>
      </div>
    );
  }

  isLast = _ => this.props.isLast || false;

  onClick = (e) => {
    e.stopPropagation();

    if (!this.isAnswer()) {
      alert('本题未答完', '未回答的题目计0分,是否进入下一题', [
        {text: this.isLast() ? '交卷' : '进入下一题', onPress: this.next},
        {text: '继续回答本题', onPress: () => console.log('继续回答')},
      ])
      return;
    }

    this.next();
  }

  /**
   * 进入下一题
   * @param _
   */
  next = _ => {
    const {history, dispatch, type} = this.props;
    if (this.isLast()) {//是最后一题,交卷
      dispatch({type: 'quiz/complete', testType: type, history});
    } else {//不是最后一题,下一题
      dispatch({type: 'quiz/next'});
    }
  }


  /**
   * 判定本题所有小题是否答完
   * @param _
   */
  isAnswer = _ => {
    const {timus = [], myAnswer = []} = this.props;

    //所有小题的id
    const tIDs = timus.reduce((m, {id}) => {
      return m.add(id);
    }, new Set());

    //去除已答id
    myAnswer.forEach(({timuId}) => tIDs.delete(timuId));

    //还有未答小题
    if (tIDs.size > 0) {
      return false;
    }
    return true;
  }

  /**
   * 下一题加一秒防抖
   * @param _
   */
  delay = _ => {
    this.setState({disabled: true});
    const a = setTimeout(_ => {
      this.setState({disabled: false})
      clearTimeout(a);
    }, 500);
  }
}

NextButton.propTypes = {};

const opts = ({quiz}) => {
  const {quizList = [], currIndex = 0, myAnswer = []} = quiz;

  const dati = quizList[currIndex] || {};
  const {timus = []} = dati;
  return {
    isLast: currIndex >= quizList.length - 1,//是否最后一题
    timus,
    myAnswer,
  };
};

export default connect(opts)(NextButton);
